package shizhan;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;
import java.io.IOException;

public class shizhan2 {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, TransformerException {
        DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();

        DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder();

        Document doc=documentBuilder.parse("src/shizhan/Phone.xml");

        Element brandElement=doc.createElement("Brand");

        brandElement.setAttribute("name","三星");

        Element typeElement=doc.createElement("Type");

        typeElement.setAttribute("name","NoteX");

        brandElement.appendChild(typeElement);

        Element phoneElement=(Element) doc.getElementsByTagName("PhoneInfo").item(0);

        phoneElement.appendChild(brandElement);

        TransformerFactory transformerFactory=TransformerFactory.newInstance();

        Transformer transformer=transformerFactory.newTransformer();

        DOMSource domSource=new DOMSource(doc);

        transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");

        StreamResult result=new StreamResult(new FileOutputStream("src/shizhan/Phone.xml"));

        transformer.transform(domSource,result);
    }
}
